import 'package:base_flutter/base_flutter.dart' as b;
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/health_check_entity.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/toast.dart';
import 'dart:convert';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:dio/dio.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:ls_work/util/utils.dart';
import 'package:ls_work/widgets/gallery_photo_browser.dart';

import '../../login/page/user_manager.dart';
import '../../util/flat_button.dart';



class MedicalPhotoListPage extends StatefulWidget {
  final HealthCheckInfo? itemInfo;
  final int? customerId;
  final int? examinationRecordId;
  final VoidCallback? callBack;
  MedicalPhotoListPage(
      {Key? key,
      this.itemInfo,
      this.callBack,
      this.customerId,
      this.examinationRecordId});
  @override
  _MedicalPhotoListPageState createState() => _MedicalPhotoListPageState();
}

class _MedicalPhotoListPageState extends State<MedicalPhotoListPage> {
  List<int> imgUrlList = [];
  int _groupValue = 3;
  TextEditingController _textFieldEditer = TextEditingController();
  @override
  void initState() {
    super.initState();

    for (var i = 0; i < (widget.itemInfo?.file??[]).length; i++) {
      print(
          '${HttpApi.imageDownLoadUrl}${widget.itemInfo!.file![i].fileId}');
      int fileId = widget.itemInfo!.file![i].fileId!;
      imgUrlList.add(fileId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.itemInfo?.itemName ?? ''}'),
        elevation: 0.5,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3, //每行三列
                childAspectRatio: 1.0, //显示区域宽高相等
                mainAxisSpacing: 10.0,
                crossAxisSpacing: 10.0,
              ),
              itemCount: (widget.itemInfo?.file??[]).length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => GalleryPhotoViewWrapper(
                          galleryItems: imgUrlList,
                          backgroundDecoration: const BoxDecoration(
                            color: Colors.black,
                          ),
                          initialIndex: index,
                        ),
                      ),
                    );
                  },
                  child: CachedNetworkImage(
                    height: 100,
                    fit: BoxFit.cover,
                    httpHeaders: {"Cookie":UserManager.cookieStr},
                    imageUrl:
                        '${HttpApi.imageDownLoadUrl}${widget.itemInfo?.file![index].fileId}',
                    placeholder: (context, url) => new ProgressView(),
                    errorWidget: (context, url, error) => new Icon(Icons.error),
                  ),
                );
              },
            ),
          ),
          widget.itemInfo?.examinationStatus == '1'
              ? _bottomView()
              : Container(),
        ],
      ),
    );
  }

  Widget _bottomView() {
    return Container(
      color: Colours.bg_color,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            width: ScreenUtil.getScreenW(context),
            height: 50,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Flexible(
                  child: Text(
                    '   审核结果：',
                    style: TextStyles.textDark20,
                  ),
                ),
                Flexible(
                  child: RadioListTile(
                    value: 3,
                    title: Text('审核通过'),
                    groupValue: _groupValue,
                    onChanged: (value) {
                      setState(() {
                        _groupValue = value!;
                      });
                    },
                  ),
                ),
                Flexible(
                  child: RadioListTile(
                    value: 2,
                    title: Text('驳回'),
                    groupValue: _groupValue,
                    onChanged: (value) {
                      setState(() {
                        _groupValue = value!;
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
          Gaps.vGap15,
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '   *备注',
                style: TextStyles.textGray18,
              ),
              Container(
                padding: EdgeInsets.fromLTRB(20, 0, 20, 20),
                alignment: Alignment.topLeft,
                height: 150,
                width: ScreenUtil.getScreenW(context) - 60,
                child: TextField(
                  controller: _textFieldEditer,
                  maxLines: 5,
                  maxLength: 150,
                  autofocus: false,
                  decoration: InputDecoration(
                    hintText: "请输入内容",
                    hintMaxLines: 20,
                    fillColor: Colors.white,
                    filled: true,
                    border: InputBorder.none,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            width: ScreenUtil.getScreenW(context),
            height: 50,
            child: FlatsButton(
              color: Colors.blue,
              highlightColor: Colors.blue[700]!,
              child: Text("提交"),
              //shape: RoundedRectangleBorder(
              //borderRadius: BorderRadius.circular(25.0)),
              onPressed: _check,
            ),
          ),
        ],
      ),
    );
  }

  ///申请审核
  _check() {
    FocusScope.of(context).unfocus();
    if (TextUtil.isEmpty(_textFieldEditer.text)) {
      Toast.show('请填写备注信息');
      return;
    }
    var map1 = {
      'customerId': widget.customerId,
      'examinationRecordId': widget.examinationRecordId,
    };
    var map2 = {
      'id': widget.itemInfo?.id,
      'examinationStatus': _groupValue,
      'reviewRemark': _textFieldEditer.text,
    };
    var date = {
      'jsonStr': jsonEncode(map1),
      'listDetail': jsonEncode([map2])
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.reviewSubmit, data: date,options: PostRequest.urlencodedHeader).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        //
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          if(widget.callBack!=null){
            widget.callBack!();
          }
          Navigator.pop(context);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
